var app = getApp()
Page({
  data: {
    isFine: true,
    cart: [],
    carts: [], // 购物车列表
    hasList: false, // 列表是否有数据
    totalPrice: '0.00', // 总价，初始为0
    selectAllStatus: false, // 全选状态，默认全选
    sum: 0,
    address : ''
  },
  onLoad: function () {
    var that = this
    if (app.globalData.phone != '') {
      that.onChecked();

    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(function (e) {
        wx.switchTab({
          url: '/pages/myself/myself',
        })
      }, 1000)
    }
  },
  onChecked() {
    //购物车
    var car = []
    var carts = app.globalData.product //全部产品
    var sum = app.globalData.product_sum //产品总数
    var that = this
    let tableName = 'shoppingcar'

    let Query = new wx.BaaS.Query()
    Query.compare('phone', '=', app.globalData.phone)
    let Product = new wx.BaaS.TableObject(tableName)
    Product.setQuery(Query).limit(1000).offset(0).find().then(res => {
      // success
      console.log(res)
      that.setData({
        cart: res.data.objects, //用户购物车全部数据
        sum: res.data.objects.length
      })

      for (var i = 0; i < that.data.sum; i++) { //全部购物车个数

        for (var j = 0; j < sum; j++) {
          if (carts[j].product_code == that.data.cart[i].product_code) {
            var cost = that.data.cart[i].name.split(',')
            var item = {
              id: i + 1,
              title: carts[j].product_name,
              image: carts[j].product_swiper_pic1,
              num: that.data.cart[i].num,
              price: carts[j].pre_cost,
              selected: false,
              product_ID: that.data.cart[i].id, //数据行id
              name: cost,
              anctual_cost: carts[j].cost
            }
          }
        }

        car.push(item)
      }
      that.setData({
        carts: car
      })
      console.log(car)
    }, err => {
      // err
    })
  },
  onShow() {
    this.setData({
      hasList: true,
      address:app.globalData.address
    });
  },
  getTotalPrice() {
    let carts = this.data.carts; // 获取购物车列表
    let total = 0;
    for (let i = 0; i < carts.length; i++) { // 循环列表得到每个数据
      if (carts[i].selected) { // 判断选中才会计算价格
        total += carts[i].num * carts[i].price; // 所有价格加起来
      }
    }
    this.setData({ // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },
  selectList(e) {
    console.log(e)
    const index = e.currentTarget.dataset.postid; // 获取data- 传进来的index
    let carts = this.data.carts; // 获取购物车列表
    console.log(index)
    console.log(carts[index])
    const selected = carts[index].selected; // 获取当前商品的选中状态
    carts[index].selected = !selected; // 改变状态
    this.setData({
      carts: carts
    });
    this.getTotalPrice(); // 重新获取总价
  },
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus; // 是否全选状态
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus; // 改变所有商品状态
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      carts: carts,
    });
    this.getTotalPrice(); // 重新获取总价
  },
  // 增加数量
  addCount(e) {
    const index = e.currentTarget.dataset.postid; //序号
    let carts = this.data.carts;
    let num = carts[index].num;
    num = num + 1;
    carts[index].num = num;
    console.log(num)
    this.setData({
      carts: carts
    });
    let tableName = 'shoppingcar'
    let recordID = this.data.carts[index].product_ID // 数据行 id
    console.log(this.data.carts[index].product_ID)
    let Product = new wx.BaaS.TableObject(tableName)
    let product = Product.getWithoutData(recordID)

    product.set('num', parseInt(num))
    product.update().then(res => {
      // success
    }, err => {
      // err
    })
    this.getTotalPrice();
  },
  // 减少数量
  minusCount(e) {
    console.log(e)
    const index = e.currentTarget.dataset.postid;
    console.log(index)
    let carts = this.data.carts;
    let num = carts[index].num;
    if (num <= 1) {
      return false;
    }
    num = num - 1;
    carts[index].num = num;
    this.setData({
      carts: carts
    });
    let tableName = 'shoppingcar'
    let recordID = this.data.carts[index].product_ID // 数据行 id
    console.log(this.data.carts[index].product_ID)
    let Product = new wx.BaaS.TableObject(tableName)
    let product = Product.getWithoutData(recordID)

    product.set('num', parseInt(num))
    product.update().then(res => {
      // success
    }, err => {
      // err
    })
    this.getTotalPrice();
  },
  deleteList(e) {
    const index = e.currentTarget.dataset.postid;
    console.log(index)
    var car = this.data.carts[index];
    console.log(car.product_ID)
    let carts = this.data.carts;
    carts.splice(index, 1); // 删除购物车列表里这个商品
    this.setData({
      carts: carts
    });
    let tableName = 'shoppingcar'
    let recordID = car.product_ID

    let Product = new wx.BaaS.TableObject(tableName)
    Product.delete(recordID).then(res => {
      // success
    }, err => {
      // err
    })
    if (!carts.length) { // 如果购物车为空
      this.setData({
        hasList: false // 修改标识为false，显示购物车为空页面
      });
    } else { // 如果不为空
      this.getTotalPrice(); // 重新计算总价格
    }
    this.onLoad()
  },
  OnDetailTap: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.postid;
    console.log(index)
    var cart = this.data.cart;
    console.log(cart)
    var product_id = cart[index].product_code
    console.log(product_id)
    setTimeout(function (e) {
      wx.navigateTo({
        url: '../post-detail/post-detail?id=' + product_id,
      })
    }, 200)

  },
  onPay: async function (e) {
    if(this.data.address == ''){
      wx.showToast({
        title: '地址未设置',
        icon:'none'
      })
      wx.navigateTo({
        url: '/pages/addAddress/addAddress?id=' + 1,
      })
    }else{
      for (var i = 0; i < this.data.carts.length; i++) {
        if (this.data.carts[i].selected == true) {
          var items = []
          var ids = ''
  
          var item = {
            产品编号: this.data.carts[i].id,
            产品名称: this.data.carts[i].title,
            数量: this.data.carts[i].num
          }
          items.push(item)
  
          console.log(items)
          console.log(ids)
          var merchandiseSnapshot = {
            电话: app.globalData.phone,
            金额: this.data.carts[i].anctual_cost - '.00',
            页面: '购物车',
            产品: this.data.carts[i].title
          }
          var name = this.data.carts[i].title + this.data.carts[i].name[0].toString()
          await app.pay_product(parseInt(this.data.carts[i].anctual_cost), name, merchandiseSnapshot, this.data.carts[i].id)
  
          var res = wx.getStorageSync('res')
          // app.globalData.isPay = true
          console.log(res)
          app.globalData.dingdanhao = res.transaction_no
  
          this.setOrder(res,i)
        }
      }
    }
    
  },
  setOrder(res,i){
    console.log('set:111')
    var that = this
    if (wx.getStorageSync('res') != '') {
      
      console.log('set:222')
      let tableName = 'Order'
      let Product = new wx.BaaS.TableObject(tableName)
      let product = Product.create()
      var myDate = new Date();
      var mytime = myDate.toLocaleString();
      console.log(mytime)
      // 设置方式一
      // let apple = {
      //   name: that.data.product_name, //商品名称
      //   sum: that.data.modal_sum, //购买数量
      //   product_code: that.data.product_code_id, //产品编号
      //   phone: app.globalData.phone, //用户手机号
      //   transaction_no: app.globalData.dingdanhao, //流水号
      //   return_money: 1, //返利钱
      //   actual_price: that.data.modal_cost - '.00', //实际价格
      //   all_price: that.data.product_item.pre_cost, //原价
      //   payment_time: mytime //时间
      // }
      console.log(that.data.modal_total.toString())
      console.log(parseInt(that.data.modal_sum))
      console.log(that.data.product_code_id.toString())
      console.log(app.globalData.phone.toString())
      console.log(res.transaction_no.toString())
      console.log((that.data.modal_cost - '.00').toString())
      console.log((that.data.product_item.pre_cost).toString())
      console.log(mytime.toString())
      console.log(that.data.address.toString())
      let apple = {
        name: that.data.carts[i].toString(),
        sum: parseInt(that.data.carts[i].num), //购买数量
        product_code: that.data.carts[i].product_ID.toString(), //产品编号
        phone: app.globalData.phone.toString(), //用户手机号
        transaction_no: res.transaction_no.toString(), //流水号
        return_money: 1, //返利钱
        actual_price: (that.data.carts[i].anctual_cost).toString(), //实际价格
        all_price: that.data.carts[i].price.toString(), //原价
        payment_time: mytime.toString(), //时间
        address: that.data.address.toString(),
        fukuan: 1
      }
      console.log(apple)
      product.set(apple).save().then(res => {
        // success
        console.log(res)
        wx.showToast({
          title: '订单创建成功',
          icon:'none'
        })
        setTimeout(function(e){
          wx.redirectTo({
            url: '../dingdan/dingdan',
          })
        },500)
      }, err => {
        //err 为 HError 对象
      })

    }
  },

})